// pages/waterDrink/waterDrink.js
import util from '../../utils/util.js';
import http from '../../utils/http.js';
const app = getApp()
let interval = null
// const maxTime = 10 * 60   // 最长10 min
Page({

  /**
   * 页面的初始数据
   */
  data: {
    percent: 0,
    time: '00:00',
    startTime: 0,
    dialogShow: false,
    normData: [], // 指标检测数据
    certificateImages: [], // 证书图片
    usageVideo: "", // 硬件设备使用视频地址
    usageVideoCover: "",
    waterWiki: [], // 矿泉水小知识
    waterOriginVideo:[], // 水源视频和标题
    waterQuantityLiveVideo: "", // 实时监控视频地址
    videoSrc: '',
    isshowMore: false, // 展示更多
    timeoutShow: false,
    isComplete: false,
    islogin: false,
    userInfoShow: false,
    avatarUrl: "",
    nickname: "",
    message: "矿主您好！饮水机正在解锁！"
  },
  _data:{
    deviceId: 0,
    maxTime: 600,
    channelId: "", // 渠道id
    channelName: "" // 渠道名字
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let scene = decodeURIComponent(options.scene);
    this._data.deviceId = options.deviceId
    this.authLogin()
    
    this.getInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.globalData.lastPath = "/pages/waterDrink/waterDrink"
    if(app.globalData.needLogin){
      wx.showModal({
        title: '提示',
        content: '您还未登录，请去首页登录！',
        showCancel: false,
        success (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/index/index',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.clear()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },
  // 开始倒计时
  startInterval(){
     interval = setInterval(()=>{
      let startTime = this.data.startTime-1
      if(startTime < 0){
        this.clear()
        if(this.data.isComplete){
          return
        }
        this.setData({
          timeoutShow: true
        })
        this.completeSure()
        return
      }
      let time = util.formatSecond(startTime)
      let percent = parseInt(((this._data.maxTime - startTime) / this._data.maxTime) * 100)
      this.setData({
        startTime: startTime,
        time: time,
        percent
      })
    },1000)
    this.data.startTime
  },
  complete(){
    if (this.data.isComplete) {
      return
    }
    this.setData({
      dialogShow: true,
      timeoutShow: false
    })
  },
  completeSure(){
    if(this.data.isComplete){
      return
    }
    this.setData({
      startTime: 0,
      time: "00:00"
    })
    this.setData({
      isComplete: true
    })
    return
    let params = {}
    params.deviceId = this._data.deviceId
    http.request("/machine/done", params)
      .then(res => {
        this.setData({
          dialogShow: false
        })
        // wx.switchTab({
        //   url: '/pages/index/index',
        // })
      })
      .catch(res => {

      })
  },
  naviToDrinkApply(){
    wx.redirectTo({
      url: '/pages/drinkApply/drinkApply?channelId=' + this._data.channelId + "&channelName=" + this._data.channelName,
    })
  },
  cancel(){
    this.setData({
      dialogShow: false
    })
  },
  getInfo(){
    http.request("/common/about")
    .then(res=>{
      this.setData({
        normData: res.data.normData,
        certificateImages: res.data.quantityCertificateImage,
        usageVideo: res.data.usageVideo,
        waterWiki: res.data.waterWiki,
        waterOriginVideo: res.data.waterOriginVideo,
        waterQuantityLiveVideo: res.data.waterQuantityLiveVideo,
        usageVideoCover: res.data.usageVideoCover
      })
    })
    .catch(res=>{

    })
  },
  getScanTime(){
    let params = {
      deviceId: this._data.deviceId
    }
    wx.showLoading({
      title: '正在解锁...',
      mask: true
    })
    http.request("/machine/scan", params)
      .then(res => {
        this._data.maxTime =  res.data.pastSecond
        let startTime = res.data.pastSecond  // this._data.maxTime - (Date.parse(new Date()) / 1000 - res.data.startTime)  
        let scanTimes = res.data.scanTimes // 判断是第几次
        this.data.startTime = startTime
        console.log(startTime)
        this._data.channelId = res.data.channelId
        this._data.channelName = res.data.channelName
        if(scanTimes != '2') {
          setTimeout(()=> {
            this.data.startTime = this.data.startTime - 3
            this.setData({
              message: "矿主您好！饮水机已打开！"
            })
            wx.hideLoading({
              success: (res) => {},
            })
           this.startInterval()
           
          },3000)
        }else{
          this.setData({
            message: "矿主您好！饮水机已打开！"
          })
          wx.hideLoading({
            success: (res) => {},
          })
         this.startInterval()
        }
      })
      .catch(res => {
        if(res.code == 90000){
          this._data.channelId = res.data.channelId
          this._data.channelName = res.data.channelName
          this.setData({
            message: res.message
          })
        }
      })
  },
  playHelpVideo(){

  },
  videoClose(){
    this.setData({
      videoSrc: ""
    })
  },
  onClose(){
    this.setData({
      timeoutShow: false
    })
  },
  playVideo(e){
    let videoSrc = e.currentTarget.dataset.src
    this.setData({
      videoSrc
    })
  },
  showMore(){
    this.setData({
      isshowMore: !this.data.isshowMore
    })
  },
  preImg(e){
    let current = e.currentTarget.dataset.img
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: this.data.certificateImages // 需要预览的图片http链接列表
    })
  },
  authLogin() {
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        let params = {
          code: res.code
        }
        http.request("/auth/login", params)
          .then(res => {
            if (res.data.status == 1) { // 1 注册过 2 未注册  
              app.globalData.needLogin = false
              wx.setStorageSync('token', res.data.token)
              this.setData({
                bindShow: false
              })
              this.getScanTime()
            } else if (res.data.status == 2) {
              // if (this.data.type == 1) { // 分享
              //   this.setData({
              //     bindShow: true
              //   })
              // }
              app.globalData.needLogin = true
              wx.showModal({
                title: '提示',
                content: '您还未登录，请去首页登录！',
                showCancel: false,
                success (res) {
                  if (res.confirm) {
                    wx.switchTab({
                      url: '/pages/index/index',
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
              this.setData({
                islogin: app.globalData.needLogin ? false : true
              })
            }
          })
          .catch(res => {

          })
      }
    })
  },
  bindGetUserInfo(e) {
    let encryptedData = e.detail.encryptedData
    let signature = e.detail.signature
    let userInfo = e.detail.userInfo
    let rawData = e.detail.rawData
    let nickname = JSON.parse(rawData).nickName
    let avatarUrl = JSON.parse(rawData).avatarUrl
    let iv = e.detail.iv
    let params = {
      encryptedData,
      iv,
      rawData,
      signature
    }
    this.setData({
      userInfoShow: true,
      islogin: true,
      avatarUrl,
      nickname
    })

  },
  getPhoneNumber(e) {
    let params = {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData,
      sessionKey: app.globalData.session.sessionKey,
      nickName: this.data.nickname,
      avatarUrl: this.data.avatarUrl,
      unionId: app.globalData.session.unionid ? app.globalData.session.unionid : "",
      openId: app.globalData.session.openid,
      deviceCode: app.globalData.deviceCode,
    }
    this.setData({
      userInfoShow: false
    })
    http.request("/auth/loginWithPhoneNumber", params)
      .then(res => {
        wx.setStorageSync('token', res.data.token)
        app.globalData.needLogin = false
        if (app.globalData.lastPath != "") {
          wx.switchTab({
            url: app.globalData.lastPath,
          })
        }
      })
      .catch(res => {

      })
  },
  clear(){
    clearInterval(interval)
    interval = null
  }
})